package com.cap.bts.crmdp.dealer.remind.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cap.bts.commonfunc.common.constant.SmsTemplateVariable;
import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.commonfunc.sms.dao.IShortMessageTemplateDao;
import com.cap.bts.commonfunc.sms.domain.SmsTemplate;
import com.cap.bts.commonfunc.sms.service.IShortMessageTemplateService;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.purchase.constants.PurchaseConstants;
import com.cap.bts.crmdp.dealer.remind.domain.CustomPromotion;
import com.cap.bts.crmdp.dealer.remind.domain.CustomerGroup;
import com.cap.bts.crmdp.dealer.remind.domain.HQPromotion;
import com.cap.bts.crmdp.dealer.remind.domain.RemindQuota;
import com.cap.bts.crmdp.dealer.remind.domain.ServiceRemind;
import com.cap.bts.crmdp.dealer.remind.dto.CustomerPromotionDto;
import com.cap.bts.crmdp.dealer.remind.dto.MsgPackageDto;
import com.cap.bts.crmdp.dealer.remind.dto.RemindDto;
import com.cap.bts.crmdp.dealer.remind.dto.RemindSubmitDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceRemindForMemberDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceRemindHistoryDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceRemindSubmitDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceTypeDto;
import com.cap.bts.crmdp.dealer.remind.service.IRemindService;
import com.cap.bts.crmdp.dealer.remind.utils.RemindUtils;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.sms.service.ISmContentService;
import com.cap.bts.framework.usermgnt.domain.User;

/**
 * 会员流程-购买
 */
@Controller
@RequestMapping(value = "/crmdp/dealer/remind")
public class RemindController extends BaseController {
   
    private static final Logger LOGGER = Logger.getLogger(RemindController.class);
    
    @Autowired
    IRemindService remindService;
    
    @Autowired
    ICodeMapping codeMapping;
    
    @Autowired
    IShortMessageTemplateService shortMessageTemplateService;
    
    @Autowired
    ISmContentService smContentService;
    
    @Autowired
    private IShortMessageTemplateDao msgTemplateDao;
    
    @RequestMapping(value = "/toRemindFromMenu")
    public String toRemindFromMenu(RemindDto dto, Model model, HttpServletRequest request)
        throws AppException {
        List<RemindDto> remindDtos=null;
        try {
           remindDtos=remindService.getRemindListByMemberNameOrMoblieOrCarPlateFromMenu(dto);
        } catch (AppException e) {
            LOGGER.error("toRemind",e);
        }
        
        CodeInfo code=codeMapping.getCodeInfoByCode("RemindDays");
        if(code!=null){
            model.addAttribute("maxRemindDays",code.getValue());
            try {
                model.addAttribute("maxRemindDate",RemindUtils.beforeTodayDays2Date(code.getValue()));
            } catch (ParseException e) {
            	LOGGER.error("toRemind",e);
            }
        }
        
        
        CodeInfo afterRemindDays=codeMapping.getCodeInfoByCode("AfterRemindDays");
        if(code!=null){
            model.addAttribute("maxAfterRemindDays",afterRemindDays.getValue());
            try {
                model.addAttribute("maxAfterRemindDate",RemindUtils.afterTodayDays2Date(afterRemindDays.getValue()));
            } catch (ParseException e) {
            	LOGGER.error("toRemind",e);
            }
        }
        
        List<ServiceTypeDto> serviceTypeDtos=new ArrayList<ServiceTypeDto>();
        List<CodeInfo> codelist=codeMapping.getCodeInfoByType("ServiceRemind");
        if(codelist!=null){
            for(CodeInfo codeinfo:codelist){
                ServiceTypeDto serviceTypeDto=new ServiceTypeDto();
                serviceTypeDto.setCode(codeinfo.getCode());
                serviceTypeDto.setServiceType(codeinfo.getValue());
                serviceTypeDto.setServiceFlag(true);
                serviceTypeDtos.add(serviceTypeDto);
            }  
        }
        if(dto.getServiceType()==null){
            model.addAttribute("serviceTypeDtos",
                serviceTypeDtos);
        }else{
            model.addAttribute("serviceTypeDtos", dto.getServiceType());
        }
        
        
        RemindQuota remindQuota=remindService.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        
        
        model.addAttribute("remindQuota",
            remindQuota);
        
        model.addAttribute("dto",
            dto);
        model.addAttribute("list",
            remindDtos);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "remind/remind";
    }
    
    @RequestMapping(value = "/toRemind")
    public String toRemind(RemindDto dto, Model model, HttpServletRequest request)
        throws AppException {
    	if(dto.getReSendFlag() == null){
    		dto.setReSendFlag("notReSendFlag");
    	}
    	if(dto.getPotentialLossFlag() == null){
    		dto.setPotentialLossFlag("potentialLossFlag");
    	}
        List<RemindDto> remindDtos=null;
        String month = dto.getqRemindStartDate();
        if(month == "" || month == null){
        	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        	String defultDate = format.format(new Date());
        	String defultMonth = defultDate.substring(0, 7);
        	model.addAttribute("maxRemindDate",defultMonth);
        }else{
        	try {
        		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        		int selectedMonthNum = Integer.parseInt(month.substring(5, 7));
        		String dateNow = format.format(new Date());
        		int dateNowNum = Integer.parseInt(dateNow.substring(5, 7));
        		int num = selectedMonthNum - dateNowNum;
        		
        		int selectedYearNum = Integer.parseInt(month.substring(0,4));
        		int dateNowYearNum = Integer.parseInt(dateNow.substring(0,4));
        		int yearNum = selectedYearNum - dateNowYearNum;
        		
        		Calendar c = Calendar.getInstance();
        		c.add(Calendar.YEAR, yearNum);
        		c.add(Calendar.MONTH, num);
        		//设置为1号,当前日期既为该月第一天
        		c.set(Calendar.DAY_OF_MONTH,1);
        		String dateNowFirst = format.format(c.getTime());
        		//获取该月最后一天
        		Calendar ca = Calendar.getInstance();
        		ca.add(Calendar.YEAR, yearNum);
        		ca.add(Calendar.MONTH, num);
        		ca.set(Calendar.DAY_OF_MONTH,ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        		String dateNowLast = format.format(ca.getTime());
        		dto.setqRemindStartDate(dateNowFirst);
        		dto.setqRemindEndDate(dateNowLast);
        	} catch (Exception e) {
        		LOGGER.error("dateFormatProcessError", e);
        	}
        }
        try {
           remindDtos=remindService.getRemindListByMemberNameOrMoblieOrCarPlate(dto);
        } catch (AppException e) {
            LOGGER.error("toRemind",e);
        }
        
        /*CodeInfo code=codeMapping.getCodeInfoByCode("RemindDays");
        if(code!=null){
            model.addAttribute("maxRemindDays",code.getValue());
            try {
                model.addAttribute("maxRemindDate",RemindUtils.beforeTodayDays2Date(code.getValue()));
            } catch (ParseException e) {
            	LOGGER.error("toRemind",e);
            }
        }
        
        
        CodeInfo afterRemindDays=codeMapping.getCodeInfoByCode("AfterRemindDays");
        if(code!=null){
            model.addAttribute("maxAfterRemindDays",afterRemindDays.getValue());
            try {
                model.addAttribute("maxAfterRemindDate",RemindUtils.afterTodayDays2Date(afterRemindDays.getValue()));
            } catch (ParseException e) {
            	LOGGER.error("toRemind",e);
            }
        }*/
        
        List<ServiceTypeDto> serviceTypeDtos=new ArrayList<ServiceTypeDto>();
        List<CodeInfo> codelist=codeMapping.getCodeInfoByType("ServiceRemind");
        if(codelist!=null){
            for(CodeInfo codeinfo:codelist){
                ServiceTypeDto serviceTypeDto=new ServiceTypeDto();
                serviceTypeDto.setCode(codeinfo.getCode());
                serviceTypeDto.setServiceType(codeinfo.getValue());
                serviceTypeDto.setServiceFlag(true);
                serviceTypeDtos.add(serviceTypeDto);
            }  
        }
        if(dto.getServiceType()==null){
            model.addAttribute("serviceTypeDtos",
                serviceTypeDtos);
        }else{
            model.addAttribute("serviceTypeDtos", dto.getServiceType());
        }
        
        
        RemindQuota remindQuota=remindService.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        
        
        model.addAttribute("remindQuota",
            remindQuota);
        dto.setDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
        model.addAttribute("dto",
            dto);
        model.addAttribute("list",
            remindDtos);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "remind/remind";
    }
    
    @RequestMapping(value = "/toRemindForCarplate")
    public String toRemindForCarplate(RemindDto dto, Model model, HttpServletRequest request)
        throws AppException {
    	List<RemindDto> remindDtos=null;
        try {
        	try {
				if(dto.getCarPlate() != null){
					dto.setCarPlate(URLDecoder.decode(dto.getCarPlate(),PurchaseConstants.ENCODE_UTF_8));
					remindDtos=remindService.getRemindListByCarPlate(dto);
				}
			} catch (UnsupportedEncodingException e) {
				LOGGER.error("toRemindForCarplate",e);
			}
        } catch (AppException e) {
            LOGGER.error("toRemindForCarplate",e);
        }
        model.addAttribute("list",remindDtos);
        try {
			model.addAttribute("carPlate",URLDecoder.decode(dto.getCarPlate(),PurchaseConstants.ENCODE_UTF_8));
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("toRemindForCarplate",e);
		}
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "remind/remindForCarplate";
    }
    
    /**
     * 
     * @Date        :      Sep 26, 2015
     * @param dto
     * @param remindDto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/sendRemindMsg")
    @ResponseBody
    public Map<String,Object> sendRemindMsg(RemindSubmitDto dto,RemindDto remindDto,Model model, HttpServletRequest request)
        throws AppException {
        Map<String,Object> rtnMap=new HashMap<String, Object>();
        rtnMap.put("result", true);
        try {
            //successMsg
            if(dto.getSendAllFlag()){
                rtnMap.putAll(remindService.sendAllRemindInfo(dto.getResendFlag(),dto.getAppSendFlag(), dto.getWechatSendFlag(), dto.getMsgSendFlag(), remindDto));
            }else{
                rtnMap.putAll(remindService.sendRemindInfoList(dto.getResendFlag(),dto.getAppSendFlag(), dto.getWechatSendFlag(), dto.getMsgSendFlag(), dto.getRemindList()));
            }
        } catch (AppException e) {
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
            LOGGER.error(e.getMessage(), e);
        }
        return rtnMap;
    }
    
    
    /**
     * 
     * @Date        :      Sep 26, 2015
     * @param dto
     * @param remindDto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/toRemindHistory")
    public String toRemindHistory(RemindDto dto, Model model, HttpServletRequest request){
        List<RemindDto> remindDtos=null;
        String month = dto.getqRemindStartDate();
        if(month == "" || month == null){
        	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        	String defultDate = format.format(new Date());
        	String defultMonth = defultDate.substring(0, 7);
        	model.addAttribute("maxRemindDate",defultMonth);
        }else{
        	try {
        		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        		int selectedMonthNum = Integer.parseInt(month.substring(5, 7));
        		String dateNow = format.format(new Date());
        		int dateNowNum = Integer.parseInt(dateNow.substring(5, 7));
        		int num = selectedMonthNum - dateNowNum;
        		
        		int selectedYearNum = Integer.parseInt(month.substring(0,4));
        		int dateNowYearNum = Integer.parseInt(dateNow.substring(0,4));
        		int yearNum = selectedYearNum - dateNowYearNum;
        		
        		Calendar c = Calendar.getInstance();
        		c.add(Calendar.YEAR, yearNum);
        		c.add(Calendar.MONTH, num);
        		//设置为1号,当前日期既为该月第一天
        		c.set(Calendar.DAY_OF_MONTH,1);
        		String dateNowFirst = format.format(c.getTime());
        		//获取该月最后一天
        		Calendar ca = Calendar.getInstance();
        		ca.add(Calendar.YEAR, yearNum);
        		ca.add(Calendar.MONTH, num);
        		ca.set(Calendar.DAY_OF_MONTH,ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        		String dateNowLast = format.format(ca.getTime());
        		dto.setqRemindStartDate(dateNowFirst);
        		dto.setqRemindEndDate(dateNowLast);
        		dto.setqStartDate(dateNowFirst);
        		dto.setqEndDate(dateNowLast);
        	} catch (Exception e) {
        		LOGGER.error("dateFormatProcessError", e);
        	}
        }
        try {
            remindDtos=remindService.getRemindHistoryList(dto);
            
            List<ServiceTypeDto> serviceTypeDtos=new ArrayList<ServiceTypeDto>();
            List<CodeInfo> codelist=codeMapping.getCodeInfoByType("ServiceRemind");
            if(codelist!=null){
                for(CodeInfo codeinfo:codelist){
                    ServiceTypeDto serviceTypeDto=new ServiceTypeDto();
                    serviceTypeDto.setCode(codeinfo.getCode());
                    serviceTypeDto.setServiceType(codeinfo.getValue());
                    serviceTypeDto.setServiceFlag(true);
                    serviceTypeDtos.add(serviceTypeDto);
                }  
            }
            if(dto.getServiceType()==null){
                model.addAttribute("serviceTypeDtos",
                    serviceTypeDtos);
            }else{
                model.addAttribute("serviceTypeDtos", dto.getServiceType());
            }
/*            if(dto.getqStartDate() == null || dto.getqStartDate().isEmpty()){
            	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            	Date date = new Date();
            	date.setDate(1);
            	model.addAttribute("maxRemindDate",sdf.format(date));
            }else{
            	model.addAttribute("maxRemindDate",dto.getqStartDate());
            }
            
            if(dto.getqEndDate() == null || dto.getqEndDate().isEmpty()){
            	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            	Date date = new Date();
            	model.addAttribute("maxAfterRemindDate",sdf.format(new Date()));
            }else{
            	model.addAttribute("maxAfterRemindDate",dto.getqEndDate());
            }
*/            
        } catch (AppException e) {
            LOGGER.error("toRemindHistory",e);
        }
        model.addAttribute("dto",
            dto);
        model.addAttribute("list",
            remindDtos);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "remind/remindHistory";
    }
    
    /**
     * 
     * @Date        :      Sep 26, 2015
     * @param dto
     * @param remindDto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/comfirmMsgPackageItem")
    @ResponseBody
    public Map<String,Object> comfirmMsgPackageItem(RemindDto remindDto,Model model, HttpServletRequest request){
        Map<String,Object> rtnMap=new HashMap<String, Object>();
        rtnMap.put("result", true);
        try {
        	if(UserUtil.getCurrentUser() == null){
        		User user = new User();
                user.setId(0L);
                user.setDealerId(Long.valueOf(remindDto.getDealerNum()));
                UserUtil.setMarsCurrentUser(user);
        	}
        	
            //sumQuantity
            rtnMap.putAll(remindService.updateLogisticProcessList(remindDto, UserUtil.getCurrentUser().getDealerId()));
        } catch (AppException e) {
            LOGGER.error("comfirmMsgPackageItem",e);
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
        }
        return rtnMap;
    }
    
    
    /**
     * 
     * @Date        :      Sep 26, 2015
     * @param dto
     * @param remindDto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/toMsgPackageList")
    public String toMsgPackageList(RemindDto dto,Model model, HttpServletRequest request){
        List<MsgPackageDto> msgPackageDtos=new ArrayList<MsgPackageDto>();
        try {
        	if(dto.getDealerNum() != null && dto.getDealerNum() != ""){
        		msgPackageDtos = remindService.getLogisticProcessListByDealerIdAndLogisticType(Long.parseLong(dto.getDealerNum()));
        	}
        } catch (AppException e) {
            LOGGER.error("toMsgPackageList",e);
        }
        if(msgPackageDtos!=null&&!msgPackageDtos.isEmpty()){
            model.addAttribute("msgPackageDtos",
                msgPackageDtos);
        }
        return "remind/msgPackageList";
    }
    
    
    /**
     * 
     * @Date        :      Sep 26, 2015
     * @param dto
     * @param remindDto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/toMsgPackageHistoryList")
    public String toMsgPackageHistoryList(RemindDto dto,Model model, HttpServletRequest request){
        List<MsgPackageDto> msgPackageDtos=new ArrayList<MsgPackageDto>();
        try {
            msgPackageDtos = remindService.getLogisticProcessHistoryListByDealerIdAndLogisticType(UserUtil.getCurrentUser().getDealerId());
        } catch (AppException e) {
            LOGGER.error("toMsgPackageHistoryList",e);
        }
        if(msgPackageDtos!=null&&!msgPackageDtos.isEmpty()){
            model.addAttribute("msgPackageDtos",
                msgPackageDtos);
        }
        return "remind/msgPackageHistoryList";
    }
    
    @RequestMapping(value = "/getRemindListSize")
    @ResponseBody
    public Map<String,Object> getRemindListSize(RemindDto dto,RemindDto remindDto,Model model, HttpServletRequest request){
        Map<String,Object> rtnMap=new HashMap<String, Object>();
        rtnMap.put("result", true);
        
        List<MsgPackageDto> msgPackageHistoryDtos;
        List<MsgPackageDto> msgPackageDtos;
        try {
             msgPackageDtos=remindService.getLogisticProcessListByDealerIdAndLogisticType(UserUtil.getCurrentUser().getDealerId());
            msgPackageHistoryDtos = remindService.getLogisticProcessHistoryListByDealerIdAndLogisticType(UserUtil.getCurrentUser().getDealerId());
            rtnMap.put("msgPackageSize", msgPackageDtos.size());
            rtnMap.put("msgPackageHistorySize", msgPackageHistoryDtos.size());
        } catch (AppException e) {
            LOGGER.error("comfirmMsgPackageItem",e);
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
        }
        
        return rtnMap;
    }
    
    @RequestMapping(value = "/toServiceRemind")
    public String toServiceRemind(ServiceRemindForMemberDto dto, Model model, HttpServletRequest request)throws AppException {
    	if(dto.getReSendFlag() == null){
    		dto.setReSendFlag("notReSendFlag");
    	}
    	if(dto.getPotentialLossFlag() == null){
    		dto.setPotentialLossFlag("potentialLossFlag");
    	}
        List<ServiceRemindForMemberDto> remindDtos=null;
        try {
           remindDtos=remindService.getRemindListByMemberNameOrMoblieOrCarPlate(dto);
        } catch (AppException e) {
            LOGGER.error("toRemind",e);
        }
        List<ServiceTypeDto> serviceTypeDtos=new ArrayList<ServiceTypeDto>();
        List<CodeInfo> codelist=codeMapping.getCodeInfoByType("ServiceRemind");
        if(codelist!=null){
            for(CodeInfo codeinfo:codelist){
                ServiceTypeDto serviceTypeDto=new ServiceTypeDto();
                serviceTypeDto.setCode(codeinfo.getCode());
                serviceTypeDto.setServiceType(codeinfo.getValue());
                serviceTypeDto.setServiceFlag(true);
                serviceTypeDtos.add(serviceTypeDto);
            }  
        }
        if(dto.getServiceType()==null){
            model.addAttribute("serviceTypeDtos",
                serviceTypeDtos);
        }else{
            model.addAttribute("serviceTypeDtos", dto.getServiceType());
        }
        dto.setDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
        model.addAttribute("dto",
            dto);
        model.addAttribute("list",
            remindDtos);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        //获取促销信息
        List<HQPromotion> hqPromotions = remindService.getHQPromotionByIsSelected(dto);
        if(hqPromotions != null && !hqPromotions.isEmpty()){
        	model.addAttribute("hqPromotion", hqPromotions.get(0));
        }
        //获取自定义促销信息
        if(dto.getMaintenanceItem() != null){
        	List<CustomPromotion> customPromotionList = remindService.getCustomerPromotionByDealerId(UserUtil.getCurrentUser().getDealerId(),dto.getMaintenanceItem());
        	model.addAttribute("customPromotionList", customPromotionList);
        }else{
        	List<CustomPromotion> customPromotionList = remindService.getCustomerPromotionByDealerId(UserUtil.getCurrentUser().getDealerId(),serviceTypeDtos.get(0).getServiceType());
        	model.addAttribute("customPromotionList", customPromotionList);
        }
        //获取车型
        List<ServiceRemind> srList = remindService.getAllServiceRemind();
        if(srList != null && !srList.isEmpty()){
        	model.addAttribute("srList",srList);
        }else{
        	model.addAttribute("srList","");
        }
        //获取客户组
        List<CustomerGroup> customerGroupList = remindService.getTrCustomerGroupByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(customerGroupList != null && !customerGroupList.isEmpty()){
        	List<String> groupTypeList = new ArrayList<String>();
        	for(CustomerGroup customerGroup :customerGroupList){
        		groupTypeList.add(customerGroup.getGroup_name());
        	}
        	model.addAttribute("groupTypeList", groupTypeList);
        }
        //获取短信 String content = generateSmsContent(smsTemplate, dto.getParaMap());
        //获取消息推送的短信模版的id
        List<SmsTemplate> list = shortMessageTemplateService.findTemplateByTemplateCode("SendRemindMsgTemplateNo", 1);
        MasterDataDealerInfo dearInfo=remindService.getDealerByDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
        if(hqPromotions != null && !hqPromotions.isEmpty()){
        	if(list != null && !list.isEmpty()){
        		SmsTemplate template = list.get(0);
        		Map<String, String> paraMap = new HashMap<String, String>();
        		paraMap.put("promotion", hqPromotions.get(0).getPromotionalContent());
        		if(dearInfo!=null){
        			paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
        			paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                }
        		String content = smContentService.generateSmsContent(template, paraMap);
        		model.addAttribute("smsTemplate",content);
        	}else{
        		model.addAttribute("smsTemplate","");
        	}
        	model.addAttribute("promotion",hqPromotions.get(0).getPromotionalContent());
        }else{
        	if(list != null && !list.isEmpty()){
        		SmsTemplate template = list.get(0);
        		Map<String, String> paraMap = new HashMap<String, String>();
        		paraMap.put("promotion", "");
        		if(dearInfo!=null){
        			paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
        			paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                }
        		String content = smContentService.generateSmsContent(template, paraMap);
        		model.addAttribute("smsTemplate",content);
        	}else{
        		model.addAttribute("smsTemplate","");
        	}
        	model.addAttribute("promotion","");
        }
        model.addAttribute("dealerId", UserUtil.getCurrentUser().getDealerId());
        return "remind/serviceRemind";
    }
    
    @RequestMapping(value = "/saveCustomerPromotion")
    @ResponseBody
    public Map<String,Object> saveCustomerPromotion(CustomerPromotionDto dto,ServiceRemindForMemberDto srDto, Model model, HttpServletRequest request)throws AppException{
    	Map<String,Object> rtnMap=new HashMap<String, Object>();
        rtnMap.put("result", true);
        try {
			if(dto.getPromotionalContent() == null || "".equals(dto.getPromotionalContent())
					|| dto.getPeriodOfValidity() == null || "".equals(dto.getPeriodOfValidity())
					|| dto.getTimeUnit() == null || "".equals(dto.getTimeUnit())){
				rtnMap.put("result", false);
	            rtnMap.put("errorMsg", "请将自定义促销填写完整。");
			}else{
				CustomPromotion customerPromotion = new CustomPromotion();
				customerPromotion.setDealerId(Long.parseLong(dto.getDealerId()));
				customerPromotion.setPromotionalContent(dto.getPromotionalContent());
				customerPromotion.setPeriodOfValidity(Long.parseLong(dto.getPeriodOfValidity()));
				customerPromotion.setTimeUnit(dto.getTimeUnit());
				customerPromotion.setMaintenanceType(srDto.getMaintenanceItem());
				remindService.saveCustomerPromotion(customerPromotion);
				rtnMap.put("result", true);
	            rtnMap.put("errorMsg", "自定义促销保存成功。");
			}
		} catch (Exception e) {
			LOGGER.error("saveCustomerPromotion",e);
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
		}
    	return rtnMap;
    }
    
    @RequestMapping(value = "/viewSMS")
    @ResponseBody
    public Map<String,Object> viewSMS(CustomerPromotionDto dto,ServiceRemindForMemberDto srDto, Model model, HttpServletRequest request)throws AppException{
    	Map<String,Object> rtnMap=new HashMap<String, Object>();
        rtnMap.put("result", true);
        try {
			if(dto.getSMSView() != null && !"".equals(dto.getSMSView())){
				Map<String, String> paraMap = new HashMap<String, String>();
				List<SmsTemplate> smsTemplates = msgTemplateDao.findTemplateByTemplateCode("SendRemindMsgTemplateNo");
				SmsTemplate smsTemplate = smsTemplates.get(0);
				if(!"-1".equals(dto.getSalesPromotion())){
					List<HQPromotion> hqPromotions = remindService.getHQPromotionByIsSelected(srDto);
			        if(hqPromotions != null && !hqPromotions.isEmpty()){
			        	if(hqPromotions.get(0).getPromotionalContent().equals(dto.getSalesPromotion())){
			        		paraMap.put("promotion", dto.getSalesPromotion());
							String content = smContentService.generateSmsContent(smsTemplate, paraMap);
							rtnMap.put("msg",content);
			        	}else{
			        		List<CustomPromotion> customerPromotions = remindService.getCustomerPromotionByPromotion(UserUtil.getCurrentUser().getDealerId(), dto.getSalesPromotion());
							if(customerPromotions != null && !customerPromotions.isEmpty()){
								CustomPromotion customPromotion = customerPromotions.get(0);
								if("day".equals(customPromotion.getTimeUnit())){
									customPromotion.setTimeUnit("天");
								}
								if("month".equals(customPromotion.getTimeUnit())){
									customPromotion.setTimeUnit("月");
								}
								if("year".equals(customPromotion.getTimeUnit())){
									customPromotion.setTimeUnit("年");
								}
								paraMap.put("promotion", dto.getSalesPromotion() + ",有效期：" + customPromotion.getPeriodOfValidity() + customPromotion.getTimeUnit());
								String content = smContentService.generateSmsContent(smsTemplate, paraMap);
								rtnMap.put("msg",content);
							}else{
								paraMap.put("promotion", "");
								String content = smContentService.generateSmsContent(smsTemplate, paraMap);
								rtnMap.put("msg",content);
							}
			        	}
			        }else{
		        		List<CustomPromotion> customerPromotions = remindService.getCustomerPromotionByPromotion(UserUtil.getCurrentUser().getDealerId(), dto.getSalesPromotion());
						if(customerPromotions != null && !customerPromotions.isEmpty()){
							CustomPromotion customPromotion = customerPromotions.get(0);
							if("day".equals(customPromotion.getTimeUnit())){
								customPromotion.setTimeUnit("天");
							}
							if("month".equals(customPromotion.getTimeUnit())){
								customPromotion.setTimeUnit("月");
							}
							if("year".equals(customPromotion.getTimeUnit())){
								customPromotion.setTimeUnit("年");
							}
							paraMap.put("promotion", dto.getSalesPromotion() + ",有效期：" + customPromotion.getPeriodOfValidity() + customPromotion.getTimeUnit());
							String content = smContentService.generateSmsContent(smsTemplate, paraMap);
							rtnMap.put("msg",content);
						}else{
							paraMap.put("promotion", "");
							String content = smContentService.generateSmsContent(smsTemplate, paraMap);
							rtnMap.put("msg",content);
						}
		        	}
				}else{
					paraMap.put("promotion", "");
					String content = smContentService.generateSmsContent(smsTemplate, paraMap);
					rtnMap.put("msg",content);
				}
			}
		} catch (Exception e) {
			LOGGER.error("viewSMS",e);
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
		}
    	return rtnMap;
    }
    
    @RequestMapping(value = "/sendServiceRemindMsg")
    @ResponseBody
    public Map<String,Object> sendServiceRemindMsg(RemindSubmitDto dto,ServiceRemindForMemberDto serviceRemindForMemberDto,CustomerPromotionDto customerDto,Model model, HttpServletRequest request)
        throws AppException {
        Map<String,Object> rtnMap=new HashMap<String, Object>();
        rtnMap.put("result", true);
        try {
            //successMsg
            if(dto.getSendAllFlag()){
                rtnMap.putAll(remindService.sendAllRemindInfo(dto.getResendFlag(),dto.getAppSendFlag(), dto.getWechatSendFlag(), dto.getMsgSendFlag(), serviceRemindForMemberDto, customerDto));
            }else{
                rtnMap.putAll(remindService.sendServiceRemindInfoList(dto.getResendFlag(),dto.getAppSendFlag(), dto.getWechatSendFlag(), dto.getMsgSendFlag(), dto.getRemindList(), customerDto));
            }
        } catch (AppException e) {
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
            LOGGER.error(e.getMessage(), e);
        }
        return rtnMap;
    }
    
    @RequestMapping(value = "/toServiceRemindHistory")
    public String toServiceRemindHistory(ServiceRemindForMemberDto dto, Model model, HttpServletRequest request)throws AppException{
        List<ServiceRemindHistoryDto> dtoList = new ArrayList<ServiceRemindHistoryDto>();
        if(dto !=null && StringUtils.isNotBlank(dto.getMobliePhone())){
        	dtoList = remindService.getServiceRemindHistoryByMobilePhone(dto);
        }
        model.addAttribute("dtoList",dtoList);
        model.addAttribute("mobile",dto.getMobliePhone());
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "remind/serviceRemindHistory";
    }
    
    @RequestMapping(value = "/toCreateCustomerGroup")
    public String toCreateCustomerGroup(ServiceRemindForMemberDto dto, Model model, HttpServletRequest request)throws AppException {
        List<ServiceRemindForMemberDto> remindDtos=null;
        try {
           remindDtos=remindService.getRemindListForCreateCustomerGroup(dto);
        } catch (AppException e) {
            LOGGER.error("toRemind",e);
        }
        dto.setDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
        //获取车型
        List<ServiceRemind> srList = remindService.getAllServiceRemind();
        if(srList != null && !srList.isEmpty()){
        	model.addAttribute("srList",srList);
        }else{
        	model.addAttribute("srList","");
        }
        model.addAttribute("dto",
            dto);
        model.addAttribute("list",
            remindDtos);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        model.addAttribute("dealerId", UserUtil.getCurrentUser().getDealerId());
        return "remind/createCustomerGroup";
    }
    
    @RequestMapping(value = "/toCreateCustomerGroupForNotice")
    public String toCreateCustomerGroupForNotice(ServiceRemindForMemberDto dto, Model model, HttpServletRequest request)throws AppException {
    	List<ServiceRemindForMemberDto> remindDtos=null;
    	try {
    		remindDtos=remindService.getRemindListForCreateCustomerGroup(dto);
    	} catch (AppException e) {
    		LOGGER.error("toRemind",e);
    	}
    	dto.setDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
    	//获取车型
    	List<ServiceRemind> srList = remindService.getAllServiceRemind();
    	if(srList != null && !srList.isEmpty()){
    		model.addAttribute("srList",srList);
    	}else{
    		model.addAttribute("srList","");
    	}
    	model.addAttribute("dto",
    			dto);
    	model.addAttribute("list",
    			remindDtos);
    	model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
    	model.addAttribute("dealerId", UserUtil.getCurrentUser().getDealerId());
    	return "remind/createCustomerGroupForNotice";
    }
    
    @RequestMapping(value = "/toSaveCustomerGroup")
    @ResponseBody
    public Map<String,Object> toSaveCustomerGroup(ServiceRemindSubmitDto srDto,ServiceRemindForMemberDto dto, Model model, HttpServletRequest request)throws AppException {
        Map<String,Object> rtnMap=new HashMap<String, Object>();
        rtnMap.put("result", true);
        try {
            if(!StringUtils.isNotBlank(dto.getGroupName())){
            	rtnMap.put("result", false);
                rtnMap.put("errorMsg", "请填写客户类型");
            }else{
            	boolean result = remindService.saveCustomerGroup(srDto, dto,UserUtil.getCurrentUser().getDealerId());
            	if(result){
            		rtnMap.put("result", true);
                    rtnMap.put("errorMsg", "保存成功");
            	}else{
            		rtnMap.put("result", false);
                    rtnMap.put("errorMsg", "保存失败");
            	}
            }
        } catch (AppException e) {
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
            LOGGER.error(e.getMessage(), e);
        }
        return rtnMap;
    }
    
    @RequestMapping(value = "/toSaveCustomerGroupForNotice")
    @ResponseBody
    public Map<String,Object> toSaveCustomerGroupForNotice(ServiceRemindSubmitDto srDto,ServiceRemindForMemberDto dto, Model model, HttpServletRequest request)throws AppException {
    	Map<String,Object> rtnMap=new HashMap<String, Object>();
    	rtnMap.put("result", true);
    	try {
    		if(!StringUtils.isNotBlank(dto.getGroupName())){
    			rtnMap.put("result", false);
    			rtnMap.put("errorMsg", "请填写客户类型");
    		}else{
    			boolean result = remindService.saveCustomerGroup(srDto, dto,UserUtil.getCurrentUser().getDealerId());
    			if(result){
    				rtnMap.put("result", true);
    				rtnMap.put("errorMsg", "保存成功");
    			}else{
    				rtnMap.put("result", false);
    				rtnMap.put("errorMsg", "保存失败");
    			}
    		}
    	} catch (AppException e) {
    		rtnMap.put("result", false);
    		rtnMap.put("errorMsg", e.getMessage());
    		LOGGER.error(e.getMessage(), e);
    	}
    	return rtnMap;
    }
    
    @RequestMapping(value = "/toDealerNotice")
    public String toDealerNotice(ServiceRemindForMemberDto dto, Model model, HttpServletRequest request)throws AppException {
    	if(dto.getReSendFlag() == null){
    		dto.setReSendFlag("notReSendFlag");
    	}
    	if(dto.getPotentialLossFlag() == null){
    		dto.setPotentialLossFlag("potentialLossFlag");
    	}
        List<ServiceRemindForMemberDto> remindDtos=null;
        try {
           remindDtos=remindService.getRemindListForNotice(dto);
        } catch (AppException e) {
            LOGGER.error("toRemind",e);
        }
        List<ServiceTypeDto> serviceTypeDtos=new ArrayList<ServiceTypeDto>();
        List<CodeInfo> codelist=codeMapping.getCodeInfoByType("ServiceRemind");
        if(codelist!=null){
            for(CodeInfo codeinfo:codelist){
                ServiceTypeDto serviceTypeDto=new ServiceTypeDto();
                serviceTypeDto.setCode(codeinfo.getCode());
                serviceTypeDto.setServiceType(codeinfo.getValue());
                serviceTypeDto.setServiceFlag(true);
                serviceTypeDtos.add(serviceTypeDto);
            }  
        }
        if(dto.getServiceType()==null){
            model.addAttribute("serviceTypeDtos",
                serviceTypeDtos);
        }else{
            model.addAttribute("serviceTypeDtos", dto.getServiceType());
        }
        dto.setDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
        model.addAttribute("dto",
            dto);
        model.addAttribute("list",
            remindDtos);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        //获取车型
        List<ServiceRemind> srList = remindService.getAllServiceRemind();
        if(srList != null && !srList.isEmpty()){
        	model.addAttribute("srList",srList);
        }else{
        	model.addAttribute("srList","");
        }
        //获取客户组
        List<CustomerGroup> customerGroupList = remindService.getTrCustomerGroupByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(customerGroupList != null && !customerGroupList.isEmpty()){
        	List<String> groupTypeList = new ArrayList<String>();
        	for(CustomerGroup customerGroup :customerGroupList){
        		groupTypeList.add(customerGroup.getGroup_name());
        	}
        	model.addAttribute("groupTypeList", groupTypeList);
        }
        //获取短信 String content = generateSmsContent(smsTemplate, dto.getParaMap());
        //获取消息推送的短信模版的id
        List<SmsTemplate> list = shortMessageTemplateService.findTemplateByTemplateCode("DealerAnnouncement", 1);
        if(list != null && !list.isEmpty()){
        	SmsTemplate template = list.get(0);
        	String templateStr = template.getMessageContent();
        	model.addAttribute("smsTemplate",templateStr);
        	
//        	Map<String, String> paraMap = new HashMap<String, String>();
//        	paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, );
        }else{
        	model.addAttribute("smsTemplate","");
        }
        model.addAttribute("dealerId", UserUtil.getCurrentUser().getDealerId());
        return "remind/dealerNotice";
    }

    @RequestMapping(value = "/viewSMSForNotice")
    @ResponseBody
    public Map<String,Object> viewSMSForNotice(CustomerPromotionDto dto, Model model, HttpServletRequest request)throws AppException{
    	Map<String,Object> rtnMap=new HashMap<String, Object>();
        rtnMap.put("result", true);
        try {
			if(dto.getSMSView() != null && !"".equals(dto.getSMSView())){
				Map<String, String> paraMap = new HashMap<String, String>();
				List<SmsTemplate> smsTemplates = msgTemplateDao.findTemplateByTemplateCode("DealerAnnouncement");
				SmsTemplate smsTemplate = smsTemplates.get(0);
				if("".equals(dto.getSalesPromotion())){
					paraMap.put("announcement", "{announcement}");
					String content = smContentService.generateSmsContent(smsTemplate, paraMap);
					rtnMap.put("msg",content);
				}else{
					paraMap.put("announcement", dto.getPromotionalContent());
					String content = smContentService.generateSmsContent(smsTemplate, paraMap);
					rtnMap.put("msg",content);
				}
			}
		} catch (Exception e) {
			LOGGER.error("viewSMS",e);
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
		}
    	return rtnMap;
    }
    
    @RequestMapping(value = "/sendServiceRemindMsgForNotice")
    @ResponseBody
    public Map<String,Object> sendServiceRemindMsgForNotice(RemindSubmitDto dto,ServiceRemindForMemberDto serviceRemindForMemberDto,CustomerPromotionDto customerDto,Model model, HttpServletRequest request)
        throws AppException {
        Map<String,Object> rtnMap=new HashMap<String, Object>();
        rtnMap.put("result", true);
        try {
            //successMsg
            if(dto.getSendAllFlag()){
                rtnMap.putAll(remindService.sendAllRemindInfoForNotice(dto.getResendFlag(),dto.getAppSendFlag(), dto.getWechatSendFlag(), dto.getMsgSendFlag(), serviceRemindForMemberDto, customerDto));
            }else{
                rtnMap.putAll(remindService.sendServiceRemindInfoListForNotice(dto.getResendFlag(),dto.getAppSendFlag(), dto.getWechatSendFlag(), dto.getMsgSendFlag(), dto.getRemindList(), customerDto));
            }
        } catch (AppException e) {
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
            LOGGER.error(e.getMessage(), e);
        }
        return rtnMap;
    }
}
